package org.destiny.config;

import java.io.Serializable;

import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.destiny.entity.StudentPO;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;

/**
 * 实现自定义接口类
 */
public class BaseRepositoryImpl<T, ID extends Serializable> extends SimpleJpaRepository<T, ID>
        implements BaseRepository<T, ID> {

    private final EntityManager entityManager;

    /**
     * @param domainClass
     * @param em
     */
    public BaseRepositoryImpl(Class<T> domainClass, EntityManager em) {
        super(domainClass, em);
        this.entityManager = em;
    }

    @Override
    public Integer countAll() {
        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
        CriteriaQuery<Long> critQuery = criteriaBuilder.createQuery(Long.class);
        Root<StudentPO> root = critQuery.from(StudentPO.class);

        critQuery.select(criteriaBuilder.countDistinct(root));
        int count = entityManager.createQuery(critQuery).getSingleResult().intValue();
        return count;
    }

}
